package com.jdk.demo.fileChannel.positionWrite;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.jdk.demo.fileChannel.batchRead.Test4_3;

public class Test7_2 {
	
	private static FileOutputStream fosRef;
	private static FileChannel fileChannel;

	// 验证write方法具有同步性
	public static void main(String[] args) throws Exception {
		fosRef = new FileOutputStream(new File("g.txt"));
		fileChannel = fosRef.getChannel();
		
		Thread thread1 = new Thread(){
			@Override
			public void run(){
				try{
					System.out.println("线程1运行");
					ByteBuffer buffer = ByteBuffer.wrap("12345".getBytes());
					fileChannel.write(buffer, 0);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		};
		Thread thread2 = new Thread(){
			@Override
			public void run(){
				try{
					System.out.println("线程2运行");
					ByteBuffer buffer = ByteBuffer.wrap("67890".getBytes());
					fileChannel.write(buffer, 0);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		};
		thread1.start();
		thread2.start();
		
		// 上述程序运行结果是哪个线程在最后运行write方法，文本文件里就是哪个线程写入的数据
		Thread.sleep(3000);
		fileChannel.close();
		fosRef.close();
	}
	
}
